電腦的世界本質上是由 0 與 1 構成的高低電位訊號。我們在螢幕上看到的文字、圖片或加密後的密文,在底層運算時都只是一連串的二進位資料:
01000001 代表 ASCII 碼中的字元 'A')。在電腦的二進位邏輯運算中(如 AND、OR、NOT 等),XOR(Exclusive OR,互斥或) 扮演了密碼學中最核心的角色。它的數學符號記作 $\oplus$。
XOR 的運算規則非常簡單直覺:「相同為 0,不同為 1」。
XOR 具備一項完美的數學特性——可逆性(Reversibility)。當我們對同一組資料用相同的金鑰進行兩次 XOR 運算時,資料就會還原回原本的樣子:
在 Java 語言中,XOR 運算主要分為以下三種常見層次:
^ 運算子)Java 對所有整數型別(byte, short, char, int, long)都支援 ^ 位元運算子。
public static void main( String[] args ) throws CharacterCodingException {
int a = 5; // 二進位: 0101
int b = 3; // 二進位: 0011
System.out.println("a:"+toBinary4(a));
System.out.println("b:"+toBinary4(b));
int c = a ^ b; // 二進位: 0110 -> 10 進位的 6
System.out.println("a ^ b:"+toBinary4(c));
// 驗證可逆性
int restored = c ^ b; // 6 ^ 3 -> 0110 ^ 0011 = 0101 (5)
System.out.println("c ^ b:"+toBinary4(restored));
}
public static String toBinary4(int value) {
int low4 = value & 0xFF;
return String.format("%4s", Integer.toBinaryString(low4)).replace(' ', '0');
}
byte[]) 的 XOR 加解密在密碼學中,我們處理的資料(明文、密文、金鑰)都是二進位的 byte[]。由於 Java 的位元運算子會在運算時自動將 byte 提升(Promotion)為 int**,因此在將結果賦值回 byte 時,必須進行強制型別轉換 (Type Cast)**。
/**
* 對輸入的 byte 陣列與 Key 進行逐位元 XOR 運算
*/
public static byte[] xorProcess(byte[] input, byte[] key) {
byte[] result = new byte[input.length];
for (int i = 0; i < input.length; i++) {
// 注意:(byte) 強制轉型不可或缺,因為 ^ 運算會自動轉成 int
result[i] = (byte) (input[i] ^ key[i % key.length]);
}
return result;
}
java.math.BigInteger)在非對稱密碼學(如 RSA、ECC)或高維度演算法中,我們經常需要處理幾百個 Bytes 的超大數字。Java 的 BigInteger 提供了內建的 .xor() 方法:
import java.math.BigInteger;
public class BigIntegerXorDemo {
public static void main(String[] args) {
BigInteger num1 = new BigInteger("123456789012345678901234567890");
BigInteger num2 = new BigInteger("987654321098765432109876543210");
// 大數 XOR 運算
BigInteger xorResult = num1.xor(num2);
// 驗證還原
BigInteger restoredNum1 = xorResult.xor(num2);
System.out.println("XOR 結果: " + xorResult);
System.out.println("還原驗證: " + restoredNum1.equals(num1)); // true
}
}